package com.core136.controller.file;

import com.alibaba.fastjson.JSON;
import com.core136.bean.account.Account;
import com.core136.bean.account.UserInfo;
import com.core136.bean.file.Attach;
import com.core136.bean.file.NetDisk;
import com.core136.bean.file.Photo;
import com.core136.common.enums.FileExt;
import com.core136.common.enums.MessageCode;
import com.core136.common.retdataunit.RetDataBean;
import com.core136.common.retdataunit.RetDataTools;
import com.core136.common.utils.FileAESUtils;
import com.core136.common.utils.SysTools;
import com.core136.service.account.AccountService;
import com.core136.service.file.AttachService;
import com.core136.service.file.NetDiskService;
import com.core136.service.file.PhotoService;
import com.core136.unit.PasswordEncryptionTools;
import com.core136.unit.fileutils.BarCodeUtils;
import com.core136.unit.fileutils.DownUtils;
import com.core136.unit.fileutils.UploadException;
import com.core136.unit.fileutils.UploadUtils;
import com.core136.unit.ueditor.UeditorConfigVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * @ClassName: FileController
 * @Description 文件上传下载Controller
 * @author: 稠云信息
 * @date: 2018年12月10日 下午1:28:36
 * @Copyright: 2018 www.cyunsoft.com Inc. All rights reserved.
 * 注意：本内容仅限于江苏稠云信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
@RestController
@RequestMapping("/sys/file")
@MultipartConfig
public class FileController {
    private UploadUtils uploadUtils;

    @Autowired
    public void setUploadUtils(UploadUtils uploadUtils) {
        this.uploadUtils = uploadUtils;
    }

    private DownUtils downUtils;

    @Autowired
    public void setDownUtils(DownUtils downUtils) {
        this.downUtils = downUtils;
    }

    private AttachService attachService;

    @Autowired
    public void setAttachService(AttachService attachService) {
        this.attachService = attachService;
    }

    private AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    private PhotoService photoService;

    @Autowired
    public void setPhotoService(PhotoService photoService) {
        this.photoService = photoService;
    }

    private NetDiskService netDiskService;

    @Autowired
    public void setNetDiskService(NetDiskService netDiskService) {
        this.netDiskService = netDiskService;
    }

    @Value("${logging.file.name}")
    private String logFilePath;
    @Value("${app.attachpath}")
    private String attachpath;
    @Value("${app.regdir}")
    private String regdirFile;
    @Value("${app.notallow}")
    private String notallow;
    @Value("${app.poi.tmppath}")
    private String tmppath;
    @Value("${app.bpm.xhtmlpath}")
    private String xhtmlpath;
    @Value("${app.host}")
    private String host;

    /**
     * Ueditor加载相关配置
     * @return
     */
    @GetMapping(value="/opt",params="action=config")
    @ResponseBody
    public Object config() {
        UeditorConfigVo config = new UeditorConfigVo();
        String urlPrefix = "";
        config.setImageUrlPrefix(urlPrefix);
        config.setVideoUrlPrefix(urlPrefix);
        config.setFileUrlPrefix(urlPrefix);
        return config;
    }

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value="/opt",params="action=uploadimage")
    @ResponseBody
    public Map<String,String> uploadImage(@RequestParam("upfile") MultipartFile file) throws Exception {
        return this.fileProcess("uploadimage",file);
    }

    /**
     * 上传视频
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value="/opt",params="action=uploadvideo")
    @ResponseBody
    public Map<String,String> uploadVideo(@RequestParam("upfile") MultipartFile file) throws Exception {
        return this.fileProcess("uploadvideo",file);
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value="/opt",params="action=uploadfile")
    @ResponseBody
    public Map<String,String> uploadFile(@RequestParam("upfile") MultipartFile file) throws Exception {
        return this.fileProcess("uploadfile",file);
    }

    /**
     * Ueditor文件上传
     * @param fileType
     * @param file
     * @return
     * @throws Exception
     */
    private Map<String,String> fileProcess(String fileType,MultipartFile file) throws Exception{
        Account account = accountService.getRedisAUserInfoToAccount();
        String partPath = SysTools.getUploadFilePath("editor");
        Map<String,String> map = new HashMap<String, String>(4);
        Attach attach = uploadUtils.upload(account,file,attachpath,partPath,notallow);
        map.put("state", "SUCCESS");
        map.put("title", attach.getNewName());
        map.put("original", attach.getNewName());
        if(fileType.equals("uploadimage")) {
            map.put("url", "/sys/file/getImage?attachId=" + attach.getAttachId());
        }else
        {
            map.put("url", "/sys/file/getFileDown?attachId=" + attach.getAttachId());
        }
        return map;
    }
    /**
     * 获取客户端二维码
     *
     * @param response
     * @param i
     */
    @RequestMapping("/getClientQRCode")
    public void getClientQRCode(HttpServletResponse response, String i) {
        try {
            String str = host;
            if (i.equals("1")) {
                str += "/datatemple/mobile/ios/oaHelper.ipa";
            } else if (i.equals("2")) {
                str += "/datatemple/mobile/android/oaHelper.pak";
            } else if (i.equals("3")) {
                str += "/datatemple/pad/ios/oaHelper.ipa";
            } else if (i.equals("4")) {
                str += "/datatemple/pad/ios/oaHelper.pak";
            }
            BarCodeUtils.getQrcodeTwo(response, str);
        } catch (Exception e) {
        }
    }

    /**
     * 获取验证码
     *
     * @param response
     * @param request
     */
    @RequestMapping("/getVerifyCodeImage")
    public void getVerifyCodeImage(HttpServletResponse response, HttpServletRequest request) {
        try {
            downUtils.getVerifyCodeImage(response, request);
        } catch (Exception e) {
        }
    }

    /**
     * 系统注册
     *
     * @param request
     * @return
     */
    @RequestMapping("/sysRegist")
    public ModelAndView sysRegist(HttpServletRequest request) {
        try {
            uploadUtils.sysRegist(request, regdirFile);
            return new ModelAndView("/");
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 系统背影图上传
     *
     * @param request
     * @param response
     */
    @RequestMapping("/uploadBackgroundImg")
    public void uploadBackgroundImg(HttpServletRequest request, HttpServletResponse response) {
        String targetpath = attachpath + File.separator + "background" + File.separator;
        PrintWriter out = null;
        try {
            RetDataBean retDataBean = RetDataTools.Ok(MessageCode.MESSAGE_IMG_UPLOAD_SUCCESS, uploadUtils.uploadImg(request, targetpath));
            String s = JSON.toJSONString(retDataBean);
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter().append(s);
            out.close();
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 上传banner图
     *
     * @param request
     * @param response
     */
    @RequestMapping("/uploadBannerImg")
    public void uploadBannerImg(HttpServletRequest request, HttpServletResponse response) {
        String targetpath = attachpath + File.separator + "vedio" + File.separator + "banner" + File.separator;
        PrintWriter out = null;
        try {
            RetDataBean retDataBean = RetDataTools.Ok(MessageCode.MESSAGE_IMG_UPLOAD_SUCCESS, uploadUtils.uploadImg(request, targetpath));
            String s = JSON.toJSONString(retDataBean);
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter().append(s);
            out.close();
        } catch (Exception e) {
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 获取banner图
     *
     * @param response
     * @param fileName
     */
    @RequestMapping("/getBannerImg")
    public void getBannerImg(HttpServletResponse response, String fileName) {
        try {
            String path = attachpath + File.separator + "vedio" + File.separator + "banner" + File.separator + fileName;
            downUtils.download(path, response);
        } catch (Exception e) {

        }
    }

    /**
     * 获取视频缩略图
     *
     * @param response
     * @param attachId
     * @param fileName
     */
    @RequestMapping("/getVideoPic")
    public void getVideoPic(HttpServletResponse response, String attachId, String fileName) {
        try {
            Account account = accountService.getRedisAUserInfoToAccount();
            Attach attach = new Attach();
            attach.setAttachId(attachId);
            attach.setOrgId(account.getOrgId());
            attach = attachService.selectOne(attach);
            String oldPath = (attachpath + attach.getPath()).replace(attach.getNewName(), "");
            oldPath = oldPath.substring(0, oldPath.length() - 1) + "pic";
            String picName = oldPath + File.separator + attach.getAttachId() + File.separator + fileName;
            downUtils.download(picName, response);
        } catch (Exception e) {
        }
    }

    /**
     * 上传专辑Logo
     *
     * @param request
     * @param response
     */
    @RequestMapping("/uploadAblumlogo")
    public void uploadAblumlogo(HttpServletRequest request, HttpServletResponse response) {
        String targetpath = attachpath + File.separator + "vedio" + File.separator + "banner" + File.separator;
        PrintWriter out = null;
        try {
            RetDataBean retDataBean = RetDataTools.Ok(MessageCode.MESSAGE_IMG_UPLOAD_SUCCESS, uploadUtils.uploadImg(request, targetpath));
            String s = JSON.toJSONString(retDataBean);
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter().append(s);
            out.close();
        } catch (Exception e) {
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 上传系统LOGO
     *
     * @param request
     * @param response
     */
    @RequestMapping("/uploadimglogo")
    public void uploadimglogo(HttpServletRequest request, HttpServletResponse response) {
        String targetpath = attachpath + File.separator + "background" + File.separator;
        PrintWriter out = null;
        try {
            RetDataBean retDataBean = RetDataTools.Ok(MessageCode.MESSAGE_IMG_UPLOAD_SUCCESS, uploadUtils.uploadImg(request, targetpath));
            String s = JSON.toJSONString(retDataBean);
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter().append(s);
            out.close();
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 图片上传
     *
     * @param request
     * @param response
     * @param module
     */
    @RequestMapping("/uploadimg")
    public void uploadimg(HttpServletRequest request, HttpServletResponse response, String module) {
        String partPath = SysTools.getUploadFilePath(module);
        PrintWriter out = null;
        try {
            RetDataBean retDataBean = RetDataTools.Ok(MessageCode.MESSAGE_IMG_UPLOAD_SUCCESS, uploadUtils.uploadImg(request, attachpath + partPath));
            String s = JSON.toJSONString(retDataBean);
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter().append(s);
            out.close();
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 获取静态图片
     *
     * @param response
     * @param module
     * @param fileName
     */
    @RequestMapping("/getStaticImg")
    public void getStaticImg(HttpServletResponse response, String module, String fileName) {
        try {
            String partPath = SysTools.getUploadFilePath(module) + File.separator + fileName;
            downUtils.download(attachpath + partPath, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 获取报表图片
     *
     * @param response
     * @param fileName
     */
    @RequestMapping("/getJasreportImg")
    public void getJasreportImg(HttpServletResponse response, String fileName) {
        try {
            downUtils.getImg(fileName, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 获取登陆背景图片
     *
     * @param response
     * @param fileName
     */
    @RequestMapping("/getBackgroundImg")
    public void getBackgroundImg(HttpServletResponse response, String fileName) {
        try {
            String path = attachpath + File.separator + "background" + File.separator + fileName;
            downUtils.download(path, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 获取BPM条形码
     *
     * @param response
     * @param codeStr
     */
    @RequestMapping("/bpm/getBarcodeOne")
    public void getBarcodeOne(HttpServletResponse response, String codeStr) {
        try {
            BarCodeUtils.getBarCodeOne(response, codeStr);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 获取BPM二维码
     *
     * @param response
     * @param codeStr
     */
    @RequestMapping("/bpm/getQrcodeTwo")
    public void getQrcodeTwo(HttpServletResponse response, String codeStr) {
        try {
            BarCodeUtils.getQrcodeTwo(response, codeStr);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }


    /**
     * 文件上传
     *
     * @param request
     * @param response
     * @param module
     */
    @RequestMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response, String module) {
        String partPath = SysTools.getUploadFilePath(module);
        PrintWriter out = null;
        try {
            Account account = accountService.getRedisAUserInfoToAccount();
            List<Attach> attachList = uploadUtils.upload(request, account, notallow, attachpath, partPath);
            if (StringUtils.isNotBlank(module)) {
                if (!module.equals("knowledge")) {
                    attachService.setLucenceIndex(attachpath, module + "Flag", attachList, account.getOrgId());
                }
            }
            RetDataBean retDataBean = RetDataTools.Ok(MessageCode.MESSAGE_ATTACH_UPLOAD_SUCCESS, attachList);
            String s = JSON.toJSONString(retDataBean);
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter().append(s);
            out.close();
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * BPM XHTML的文件上传
     *
     * @param request
     * @param response
     */
    @RequestMapping("/bpmTemplateFileUpLoad")
    public void bpmTemplateFileUpLoad(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            RetDataBean retDataBean = RetDataTools.Ok(MessageCode.MESSAGE_ATTACH_UPLOAD_SUCCESS, uploadUtils.uploadXhtml(request, xhtmlpath));
            String s = JSON.toJSONString(retDataBean);
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter().append(s);
            out.close();
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 头像上传
     *
     * @param request
     * @param response
     */
    @RequestMapping("/uploadHeadImg")
    public void uploadHeadImg(HttpServletRequest request, HttpServletResponse response) {
        String targetpath = attachpath + File.separator + "headimg" + File.separator;
        PrintWriter out = null;
        try {
            uploadUtils.uploadHeadImg(request, targetpath);
            RetDataBean retDataBean = RetDataTools.Ok(MessageCode.MESSAGE_HEADING_SUCESS);
            String s = JSON.toJSONString(retDataBean);
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter().append(s);
            out.close();
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * OnlyOffice在线打开文件
     *
     * @param response
     * @param request
     * @param accountId
     * @param orgId
     */
    @RequestMapping("/getFileDownForOnlyOffice")
    public void getFileDownForOnlyOffice(HttpServletResponse response, HttpServletRequest request, String accountId, String orgId) {
        try {
            Account account = new Account();
            account.setAccountId(accountId);
            account.setOrgId(orgId);
            account = accountService.selectOneAccount(account);
            String attachId = request.getParameter("attachId");
            String netDiskId = request.getParameter("netDiskId");
            String path = request.getParameter("attachId");
            if (StringUtils.isNotBlank(netDiskId)) {
                NetDisk netDisk = new NetDisk();
                netDisk.setNetDiskId(netDiskId);
                netDisk.setOrgId(account.getOrgId());
                netDisk = netDiskService.selectOneNetDisk(netDisk);
                path = netDisk.getRootPath() + path;
                path = path.replace("\\", File.separator).replace("/", File.separator);
                String fileName = path.substring(path.lastIndexOf(File.separator) + 1, path.length());
                String utf8filename = URLEncoder.encode(fileName, "UTF-8");
                response.setHeader("Content-disposition", "attachment; filename=" + utf8filename);
                response.setContentType("application/octet-stream");
                downUtils.download(path, response);
            } else {
                Attach attach = new Attach();
                attach.setAttachId(attachId);
                attach.setOrgId(account.getOrgId());
                attach = attachService.selectOne(attach);
                if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                    File file = new File(attachpath + attach.getPath());
                    String fileName = file.getName();
                    String utf8filename = URLEncoder.encode(fileName, "UTF-8");
                    response.setHeader("Content-disposition", "attachment; filename=" + utf8filename);
                    response.setContentType("application/octet-stream");
                    FileAESUtils.decryptFileToDown(attach.getEncryptKey(), attachpath + attach.getPath(), response);
                } else {
                    downUtils.download(attachpath + attach.getPath(), response);
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 文件下载
     *
     * @param response
     * @param request
     */
    @RequestMapping("/getFileDown")
    public void getFileDown(HttpServletResponse response, HttpServletRequest request) {
        try {
            Account account = accountService.getRedisAUserInfoToAccount();
            String attachId = request.getParameter("attachId");
            String netDiskId = request.getParameter("netDiskId");
            String path = request.getParameter("path");
            if(StringUtils.isNotBlank(netDiskId))
            {
                NetDisk netDisk = new NetDisk();
                netDisk.setNetDiskId(netDiskId);
                netDisk.setOrgId(account.getOrgId());
                netDisk = netDiskService.selectOneNetDisk(netDisk);
                //path = URLDecoder.decode(path);
                path = netDisk.getRootPath() + path;
                path = path.replace("\\", File.separator).replace("/", File.separator);
                downUtils.download(path, response);
            }else {
                Attach attach = new Attach();
                attach.setAttachId(attachId);
                attach.setOrgId(account.getOrgId());
                attach = attachService.selectOne(attach);
                if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                    File file = new File(attachpath + attach.getPath());
                    String fileName = file.getName();
                    String utf8filename = URLEncoder.encode(fileName, "UTF-8");
                    response.setHeader("Content-Disposition", "attachment; filename=" + utf8filename);
                    response.setContentType("application/octet-stream");
                    FileAESUtils.decryptFileToDown(attach.getEncryptKey(), attachpath + attach.getPath(), response);
                } else {
                    downUtils.download(attachpath + attach.getPath(), response);
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 在线打开文件
     *
     * @param response
     * @param request
     */
    @RequestMapping("/openFileOnLine")
    public void openFileOnLine(HttpServletResponse response, HttpServletRequest request) {
        try {
            String sessionId = request.getParameter("sessionId");
            String netDiskId = request.getParameter("netDiskId");
            String path = request.getParameter("path");
            UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
            if (userInfo == null) {
                if (StringUtils.isNotBlank(sessionId)) {
                    userInfo = accountService.getRedisAUserInfoToUserInfo(sessionId);
                }
            }
            if (StringUtils.isNotBlank(netDiskId)) {
                NetDisk netDisk = new NetDisk();
                netDisk.setNetDiskId(netDiskId);
                netDisk.setOrgId(userInfo.getOrgId());
                netDisk = netDiskService.selectOneNetDisk(netDisk);
                path = path.replace("\\", File.separator).replace("/", File.separator);
                path = netDisk.getRootPath() + path;
                String fileName = path.substring(path.lastIndexOf(File.separator) + 1, path.length());
                String utf8filename = URLEncoder.encode(fileName, "UTF-8");
                response.setHeader("Content-disposition", "attachment; filename=" + utf8filename);
                response.setContentType("application/octet-stream");
                downUtils.openFileOnLine(path, response, "");
            } else {
                String attachId = request.getParameter("attachId");
                Attach attach = new Attach();
                attach.setAttachId(attachId);
                attach.setOrgId(userInfo.getOrgId());
                attach = attachService.selectOne(attach);
                if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                    File file = new File(attachpath + attach.getPath());
                    String filename = file.getName();
                    String extName = filename.substring(filename.lastIndexOf("."), filename.length());
                    if (extName.toUpperCase().equals(".UOF")) {
                        filename = filename.substring(0, filename.lastIndexOf(".")) + ".doc";
                    }
                    String utf8filename = URLEncoder.encode(filename, "UTF-8");
                    response.setHeader("Content-disposition", "attachment; filename=" + utf8filename);
                    FileAESUtils.decryptFileToDown(attach.getEncryptKey(), attachpath + attach.getPath(), response);
                    response.setContentType("application/octet-stream");
                } else {
                    downUtils.openFileOnLine(attachpath + attach.getPath(), response, attach.getEncryptKey());
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 获取账户头像
     *
     * @param response
     */
    @RequestMapping("/getHeadImg")
    public void getHeadImg(HttpServletResponse response) {
        try {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            String headImg = session.getAttribute("headImg").toString();
            String path = attachpath + File.separator + "headimg" + File.separator + headImg;
            downUtils.getUserHeadimg(path, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 获取他人头像
     *
     * @param response
     * @param headImg
     */
    @RequestMapping("/getOtherHeadImg")
    public void getOtherHeadImg(HttpServletResponse response, String headImg) {
        try {
            String path = attachpath + File.separator + "headimg" + File.separator + headImg;
            downUtils.getUserHeadimg(path, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 获取Im中的文件
     *
     * @param response
     * @param attachId
     */
    @RequestMapping("/getImFile")
    public void getImFile(HttpServletResponse response, String attachId) {
        try {
            Attach attach = new Attach();
            attach.setAttachId(attachId);
            attach = attachService.getAttachById(attach);
            downUtils.Imdownload(attachpath + attach.getPath(), response, 2);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }


    /**
     * 获取图片
     *
     * @param response
     * @param attach
     * @param netDisk
     * @param path
     */
    @RequestMapping("/getImage")
    public void getImage(HttpServletResponse response, Attach attach, NetDisk netDisk, String path) {
        try {
            Account account = accountService.getRedisAUserInfoToAccount();
            String imgepath = SysTools.getAppDir() + File.separator + "static" + File.separator + "gobal" + File.separator + "img" + File.separator + "error.jpg";
            if (StringUtils.isBlank(attach.getAttachId())) {
                netDisk.setOrgId(account.getOrgId());
                netDisk = netDiskService.selectOneNetDisk(netDisk);
                imgepath = netDisk.getRootPath() + URLDecoder.decode(path,"utf-8");
                downUtils.getImg(imgepath, response);
            } else {
                attach.setOrgId(account.getOrgId());
                attach = attachService.selectOne(attach);
                if (attach != null) {
                    if (StringUtils.isBlank(attach.getEncryptKey())) {
                        if (FileExt.getFileextmap().get("img").indexOf("," + attach.getExtName() + ",") > -1) {
                            imgepath = attachpath + attach.getPath();
                        }
                        downUtils.getImg(imgepath, response);
                    } else {
                        imgepath = attachpath + attach.getPath();
                        File file = new File(attachpath + attach.getPath());
                        String filename = file.getName();
                        String utf8filename = URLEncoder.encode(filename, "UTF-8");
                        response.setHeader("Content-disposition", "attachment; filename=" + utf8filename);
                        response.setContentType("image/jpeg");
                        FileAESUtils.decryptFileToDown(attach.getEncryptKey(), imgepath, response);
                    }
                } else {
                    imgepath = SysTools.getAppDir() + File.separator + "static" + File.separator + "gobal" + File.separator + "img" + File.separator + "error.jpg";
                    downUtils.getImg(imgepath, response);
                }
            }
        } catch (Exception e) {
        }
    }

    /**
     * 按attachIds获取附件列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/getAttachList")
    public RetDataBean getAttachList(HttpServletRequest request) {
        try {
            String attachIds = request.getParameter("attachIds");
            List<String> attachList = new ArrayList<String>();
            if (StringUtils.isNotEmpty(attachIds)) {
                String[] attachArray = attachIds.split(",");
                attachList = Arrays.asList(attachArray);
            } else {
                RetDataTools.Fail(MessageCode.MESSAGE_REQUEST_ERROR);
            }
            if (attachList.size() > 0) {
                return RetDataTools.Ok(MessageCode.MESSAGE_REQUEST_SUCCESS, attachService.getAttachList(attachList));
            } else {
                return RetDataTools.NotOk(MessageCode.MESSAGE_REQUEST_ERROR);
            }
        } catch (Exception e) {
            return RetDataTools.Error(e.getMessage());
        }
    }

    /**
     * 附件逻辑删除
     *
     * @param attach
     * @return
     */
    @RequestMapping("/delAttch")
    public RetDataBean delAttach(Attach attach) {
        try {
            Account account = accountService.getRedisAUserInfoToAccount();
            attach.setOrgId(account.getOrgId());
            if (!account.getOpFlag().equals("1")) {
                attach.setCreateAccount(account.getAccountId());
                if (attachService.deleteAttach(attach) > 0) {
                    return RetDataTools.Ok(MessageCode.MESSAGE_ATTACH_DELETE_SUCCESS, 1);
                } else {
                    return RetDataTools.NotOk(MessageCode.MESSAGE_ATTACH_DELETE_FAIL);
                }
            } else {
                if (attachService.deleteAttach(attach) > 0) {
                    return RetDataTools.Ok(MessageCode.MESSAGE_ATTACH_DELETE_SUCCESS);
                } else {
                    return RetDataTools.NotOk(MessageCode.MESSAGE_ATTACH_DELETE_FAIL);
                }
            }
        } catch (Exception e) {
            return RetDataTools.Error(e.getMessage());
        }
    }

    /**
     * 查看系统运行日志
     *
     * @param response
     * @param fileName
     */
    @RequestMapping(value = "/getReadSystemLog", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public void getReadSystemLog(HttpServletResponse response, String fileName) {
        try {
            Account account = accountService.getRedisAUserInfoToAccount();
            if (account == null) {
                return;
            }
            File file = new File(logFilePath);
            String path = file.getParentFile().getAbsolutePath() + File.separator + fileName;
            downUtils.readLogFile(path, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * @param response
     * @return void
     * @Title readFile
     * @Description  在线查看文件
     */
    @RequestMapping(value = "/readFile", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public void readFile(HttpServletResponse response, Attach attach, NetDisk netDisk, String path) {
        try {
            String attachPath = "";
            Account account = accountService.getRedisAUserInfoToAccount();
            if (StringUtils.isNotBlank(attach.getAttachId())) {
                attach.setOrgId(account.getOrgId());
                attach = attachService.selectOne(attach);
                if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                    response.setHeader("Content-type", "text/html;charset=UTF-8");
                    response.addHeader("Content-Length", "" + attach.getFileSize());
                    response.setHeader("Content-Disposition", "inline; filename=" + new String(attach.getOldName().getBytes("utf-8"), "ISO8859-1"));
                    ByteArrayOutputStream outArr = FileAESUtils.decryptFileToFileInputStream(attach.getEncryptKey(), attachpath + attach.getPath());
                    OutputStream out = response.getOutputStream();
                    outArr.writeTo(out);
                    out.close();
                } else {
                    attachPath = attachpath + attach.getPath();
                    downUtils.readFile(attachPath, response);
                }
            } else {
                netDisk.setOrgId(account.getOrgId());
                netDisk = netDiskService.selectOneNetDisk(netDisk);
                attachPath = netDisk.getRootPath() + path;
                downUtils.readFile(attachPath, response);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * IM文件上传
     *
     * @param request
     * @param module
     * @param accountId
     * @param passWord
     * @return
     */
    @RequestMapping("/imUpload")
    public RetDataBean imUpload(HttpServletRequest request, String module, String accountId, String passWord) {
        String partPath = SysTools.getUploadFilePath(module);
        try {
            Account account = accountService.getLoginAccount(accountId, PasswordEncryptionTools.getEnPassWord(accountId + passWord));
            return RetDataTools.Ok(MessageCode.MESSAGE_ATTACH_UPLOAD_SUCCESS, uploadUtils.ImUpload(request, account, notallow, attachpath, partPath));
        } catch (IOException e) {
            return RetDataTools.Error(e.getMessage());
        } catch (UploadException e) {
            return RetDataTools.Error(e.getMessage());
        }
    }

    /**
     * 接收语言文件
     *
     * @param request
     * @param module
     * @param accountId
     * @param passWord
     * @return
     */
    @RequestMapping("/imAudioUpload")
    public RetDataBean imAudioUpload(HttpServletRequest request, String module, String accountId, String passWord) {
        String partPath = SysTools.getUploadFilePath(module);
        try {
            Account account = accountService.getLoginAccount(accountId, PasswordEncryptionTools.getEnPassWord(accountId + passWord));
            return RetDataTools.Ok(MessageCode.MESSAGE_ATTACH_UPLOAD_SUCCESS, uploadUtils.ImAudioUpload(request, account, notallow, attachpath + partPath));
        } catch (IOException e) {
            return RetDataTools.Error(e.getMessage());
        } catch (UploadException e) {
            return RetDataTools.Error(e.getMessage());
        }
    }

    /**
     * 从服务器上获取语音文件
     *
     * @param response
     * @param fileName
     */
    @RequestMapping("/getImAudioFile")
    public void getImAudioFile(HttpServletResponse response, String fileName) {
        try {
            String attachId = fileName.substring(0, fileName.lastIndexOf("."));
            Attach attach = new Attach();
            attach.setAttachId(attachId);
            attach = attachService.getAttachById(attach);
            downUtils.download(attachpath + attach.getPath(), response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * @param response
     * @Title: getImAttachFile
     * @Description:  下载IM附件
     */
    @RequestMapping("/getImAttachFile")
    public void getImAttachFile(HttpServletResponse response, String attachId) {
        try {
            Attach attach = new Attach();
            attach.setAttachId(attachId);
            attach = attachService.getAttachById(attach);
            downUtils.download(attachpath + attach.getPath(), response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }


    /**
     * @Title: getImgByPath
     * @Description:  按服务器目录获取网络图片
     * @param: response
     * @param: request
     * @param: imgName
     * @return: void
     */
    @RequestMapping("/getImgByPath")
    public void getImgByPath(HttpServletResponse response, String imgName, String filetage) {
        try {
            String path = tmppath + File.separator + filetage + File.separator + "image" + File.separator + imgName;
            downUtils.download(path, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    @RequestMapping("/getOpenOfficeImg")
    public void getOpenOfficeImg(HttpServletResponse response, String imgName, String filetage) {
        try {
            String path = tmppath + File.separator + filetage + File.separator + imgName;
            downUtils.download(path, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }


    /**
     * @Title: getPhotoImg
     * @Description:  获取相册下的图片
     * @param: response
     * @param: request
     * @param: fileName
     * @param: photo
     * @return: void
     */
    @RequestMapping("/getPhotoImg")
    public void getPhotoImg(HttpServletResponse response, String fileName, Photo photo) {
        try {
            Account account = accountService.getRedisAUserInfoToAccount();
            photo.setOrgId(account.getOrgId());
            photo = photoService.selectOnePhoto(photo);
            String path = photo.getRootPath() + File.separator + fileName;
            downUtils.getImg(path, response);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }
}
